package codeRandomThoughts.Test257二叉树的所有路径;

import codeRandomThoughts.utils.TreeNode;

import java.util.ArrayList;
import java.util.List;

public class Solution {
    public List<String> binaryTreePaths(TreeNode root) {
        List<String> res = new ArrayList<>();
        if (root == null) {
            return res;
        }
        List<Integer> path = new ArrayList<>();
        backTrack(root, path, res);
        return res;
    }

    void backTrack(TreeNode root, List<Integer> path, List<String> result) {
        path.add(root.val);
        //到叶子节点为终止条件
        if (root.left == null && root.right == null) {
            //把结果添加到result中
            //格式转换
            result.add(format(path));
            return;
        }

        //递归 本应该是for循环,但是每层就两个,相当于是直接模拟了,即从左往右遍历
        //不进去空结点
        if (root.left != null) {
            backTrack(root.left, path, result);
            path.remove(path.size() - 1);
        }
        if (root.right != null) {
            backTrack(root.right, path, result);
            path.remove(path.size() - 1);
        }
    }

    String format(List<Integer> path) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < path.size() - 1; i++) {
            sb.append(path.get(i)).append("->");
        }
        return sb.append(path.get(path.size() - 1)).toString();
    }

    private void traversal(TreeNode root, List<Integer> paths, List<String> res) {
        paths.add(root.val);

        //如果是叶子节点
        if (root.left == null && root.right == null) {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < paths.size() - 1; i++) {
                sb.append(paths.get(i)).append("->");
            }
            //最后一个节点单独添加
            sb.append(paths.get(paths.size() - 1));
            res.add(sb.toString());
            return;
        }

        if (root.left != null) {
            traversal(root.left, paths, res);
            paths.remove(paths.size() - 1);//回溯
        }
        if (root.right != null) {
            traversal(root.right, paths, res);
            paths.remove(paths.size() - 1);//回溯
        }
    }
}
